<template>
  <div>
    <el-dialog :visible="showDialog" v-bind="$attrs" :title="form.id?'编辑部门':'新增部门'" v-on="$listeners" @open="onOpen" @close="close">
      <el-form ref="formRef" :model="form" :rules="rules" size="medium" label-width="100px">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入部门名称" clearable :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入部门编码" clearable :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="部门负责人" prop="manager">
          <el-select v-model="form.manager" placeholder="请选择部门负责人" clearable :style="{width: '100%'}">
            <el-option
              v-for="(item, index) in managerOptions"
              :key="index"
              :label="item.username"
              :value="item.username"
              :disabled="item.disabled"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input
            v-model="form.introduce"
            type="textarea"
            placeholder="请输入部门介绍"
            :autosize="{minRows: 4, maxRows: 4}"
            :style="{width: '100%'}"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-row slot="footer" type="flex" justify="center">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handelConfirm">确定</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { getEmployeeSimple } from '../../../api/user.js'
import { getDepartments, addDepartments, updateDepartment } from '../../../api/departments.js'

export default {
  components: {},
  inheritAttrs: false,
  props: {
    showDialog: {
      type: Boolean,
      required: true
    },
    node: {
      type: Object,
      required: true
    }
  },
  data() {
    const validateName = async(rule, value, callback) => {
      // 同级部门中禁止出现重复部门
      // 理解,这句话包含哪些数据
      // 当前输入的部门名称 this.form.name或者value
      // 父部门(点击新增,传到子组件当中)this.node
      //   let pid = this.node.id
      // 所有部门const { depts } = await getDepartments()
      // 同级部门(兄弟部门)
      //   let brothers = depts.filter(t=> t.pid === pid)
      // 判断是有重复
      //   brothers.some(t=> t.name === value)
      /* ==============================⭐ 👇 ==============================*/
      // const pid = this.node.id
      // const { depts } = await getDepartments()
      // const brothers = depts.filter(t => t.pid === pid)
      // console.log(brothers)

      // if (brothers.some(t => t.name === value)) {
      //   callback(new Error('不能重复'))
      // } else {
      //   callback()
      // }
      /* ==============================⭐ 链式调用 👇==============================*/
      let depts = (await getDepartments()).depts
      if (this.form.id) {
        depts = depts.filter(t => t.id !== this.form.id && t.pid === this.form.pid)
        // 排除同部门同名称的（t.pid === this.form.pid 相等的话，就不能重命名部门兄弟），
        // 编辑可以修改自己（t.id !== this.form.id排除自己就可以修改自己了）
      } else {
        depts = depts.filter(t => t.pid === this.node.id)
      }

      if (depts.some(t => t.name === value)) {
        callback(new Error('不能重复'))
      } else {
        callback()
      }
      /* ==============================⭐  ==============================*/
    }

    const validateCode = async(rule, value, callback) => {
      // 部门编码在整个模块中都不允许重复
      // 理解,这句话包含哪些数据
      // 部门编码(当前输入部门编码) this.form.code或者value
      // 整个模块(所有部门)const { depts } = await getDepartments()
      // 不允许重复,depts.some(t=> t.code === value)
      let { depts } = await getDepartments()
      console.log(depts, '这是添加规则验证的函数')
      if (this.form.id) {
        // 允许编辑本部门，但要排除当前部门
        depts = depts.filter(t => t.id !== this.form.id)// 编辑部门查重，排除本部门
      }
      if (depts.some(t => t.code === value)) {
        callback(new Error('不能重复'))
      } else {
        callback()
      }
    }
    return {
      form: {
        name: undefined,
        code: undefined,
        manager: undefined,
        introduce: undefined
      },
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { validator: validateName, trigger: 'blur' }],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { validator: validateCode, trigger: 'blur' }
        ],
        manager: [{
          required: true, message: '请选择部门负责人', trigger: 'change'
        }],
        introduce: [{
          required: true, message: '请输入部门介绍', trigger: 'blur' },
        { min: 1, max: 300, message: '部门名称要求1-300个字符', trigger: 'blur' }]
      },
      managerOptions: []
    }
  },
  computed: {},
  // watch: {
  //   // 法一：通过监听变量修改form，显示编辑表单
  //   node(val) {
  //     this.form = val
  //   }
  // },
  created() {
    this.getEmployeeSimpleFn()
  },
  mounted() {},
  methods: {
    onOpen() {},
    close() {
      // 对整个表单进行重置，将所有字段值重置为初始值并移除校验结果
      // 理解做那几件事情
      // (1)将所有字段值重置为初始值
      //    所有字段值,是el-form-item配置了prop的字段
      //    初始值,不是最开始data的值,在对话框显示之前data最后的值
      // (2)移除校验结果
      //    去除校验红色提示
      this.form = {
        name: undefined,
        code: undefined,
        manager: undefined,
        introduce: undefined
      }// 手动重置数据
      this.$refs['formRef'].resetFields()
      this.$emit('update:showDialog', false)
    },
    handelConfirm() {
      this.$refs['formRef'].validate(async valid => {
        if (!valid) return
        // 发请求
        if (this.form.id) {
          // 编辑==>
          await updateDepartment(this.form)
        } else {
          // 新增===>
          await addDepartments({
            ...this.form,
            pid: this.node.id
          })
        }

        // 提示成功
        this.$message.success('操作成功')
        // 刷新列表
        this.$emit('success')
        // 关闭对话框
        this.close()
      })
    },
    async getEmployeeSimpleFn() {
      const res = await getEmployeeSimple()
      this.managerOptions = res
    }
  }
}

</script>
<style>
</style>
